using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Sheep_Breeding.Domain;
using Sheep_Breeding.Domain.production_b;
using Sheep_Breeding.ErrorCode;
using Sheep_Breeding.Infeartructure;
using Sheep_Breeding.Write.Api.DTOs;
using Sheep_Breeding.Write.Api.OperationServices.IServices;

namespace Sheep_Breeding.Write.Api.OperationServices.Services
{
    /// <summary>
    /// 羊只采购服务实现类
    /// </summary>
    public class SheepPurchaseServices : ISheepPurchaseServices
    {
        private readonly ILogger<SheepPurchaseServices> logger;
        private readonly IMapper mapper;
        private readonly IBaseRepository<SheepPurchase> sheepPurchaseRepository;
        private readonly EFDbContext db;

        public SheepPurchaseServices(
            ILogger<SheepPurchaseServices> logger,
            IMapper mapper,
            IBaseRepository<SheepPurchase> sheepPurchaseRepository,
            EFDbContext db)
        {
            this.logger = logger;
            this.mapper = mapper;
            this.sheepPurchaseRepository = sheepPurchaseRepository;
            this.db = db;
        }

        /// <summary>
        /// 羊只采购添加
        /// </summary>
        /// <param name="dto">添加羊只采购信息</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> AddSheepPurchase(AddSheepPurchaseDto dto)
        {
            logger.LogInformation("羊只采购信息添加操作");
            var res = new ApiResult();

            try
            {
                // 验证DTO
                if (dto == null)
                {
                    res.msg = "请求数据不能为空";
                    logger.LogWarning("请求数据为空");
                    return res;
                }

                logger.LogInformation($"开始映射DTO，采购员ID: {dto.PurchaserId}, 采购日期: {dto.PurchaseDate}");

                // 映射DTO到实体
                var model = mapper.Map<SheepPurchase>(dto);

                if (model == null)
                {
                    res.msg = "数据映射失败";
                    logger.LogError("AutoMapper映射失败");
                    return res;
                }

                logger.LogInformation("DTO映射成功，开始设置创建信息");

                // 设置创建时间
                model.CreateTime = DateTime.Now;
                model.CreateUserId = dto.PurchaserId.ToString(); // 假设采购员就是创建人
                model.ApprovalUserId = null; // 新增时审核人为空
                model.ApprovalTime = null; // 新增时审核时间为空

                logger.LogInformation($"准备添加到数据库，实体信息: ID={model.Id}, 采购员={model.PurchaserId}, 创建时间={model.CreateTime}");

                // 添加到数据库
                var info = await sheepPurchaseRepository.AddAsyn(model);

                logger.LogInformation($"数据库操作完成，影响行数: {info}");

                if (info > 0)
                {
                    res.success("羊只采购信息添加成功");
                    logger.LogInformation($"羊只采购信息添加成功，ID: {model.Id}");
                }
                else
                {
                    res.msg = "羊只采购信息添加失败";
                    logger.LogWarning("羊只采购信息添加失败");
                }

                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"羊只采购信息添加异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"添加羊只采购信息失败: {ex.Message}";
                return res;
            }
        }

        /// <summary>
        /// 羊只采购删除
        /// </summary>
        /// <param name="dto">删除羊只采购信息</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> DeleteSheepPurchase(DeleteSheepPurchaseDto dto)
        {
            logger.LogInformation($"羊只采购信息删除操作，ID: {dto.Id}");
            var res = new ApiResult();

            try
            {
                // 获取要删除的记录
                var info = await sheepPurchaseRepository.GetValue(x => x.Id.Equals(dto.Id));

                if (info != null)
                {
                    // 逻辑删除：设置删除标志
                    info.IsDele = true;
                    info.UpdateTime = DateTime.Now;
                    info.UpdateUserId = dto.Id.ToString(); // 这里应该传入当前用户ID

                    var model = await sheepPurchaseRepository.Update(info);

                    if (model > 0)
                    {
                        res.success("删除成功");
                        logger.LogInformation($"羊只采购信息删除成功，ID: {dto.Id}");
                    }
                    else
                    {
                        res.msg = "删除失败";
                        logger.LogWarning($"羊只采购信息删除失败，ID: {dto.Id}");
                    }
                }
                else
                {
                    res.msg = "记录不存在";
                    logger.LogWarning($"羊只采购信息不存在，ID: {dto.Id}");
                }

                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"羊只采购信息删除异常: {ex.Message}");
                throw ex;
            }
        }

        /// <summary>
        /// 羊只采购更新
        /// </summary>
        /// <param name="dto">更新羊只采购信息</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> UpdateSheepPurchase(UpdateSheepPurchaseDto dto)
        {
            logger.LogInformation($"羊只采购信息更新操作，ID: {dto.Id}");
            var res = new ApiResult();

            try
            {
                // 获取要更新的记录
                var existingRecord = await sheepPurchaseRepository.GetValue(x => x.Id.Equals(dto.Id));

                if (existingRecord != null)
                {
                    // 映射DTO到实体
                    mapper.Map(dto, existingRecord);

                    // 设置更新时间
                    existingRecord.UpdateTime = DateTime.Now;
                    existingRecord.UpdateUserId = dto.PurchaserId.ToString(); // 这里应该传入当前用户ID

                    var model = await sheepPurchaseRepository.Update(existingRecord);

                    if (model > 0)
                    {
                        res.success("羊只采购信息更新成功");
                        logger.LogInformation($"羊只采购信息更新成功，ID: {dto.Id}");
                    }
                    else
                    {
                        res.msg = "羊只采购信息更新失败";
                        logger.LogWarning($"羊只采购信息更新失败，ID: {dto.Id}");
                    }
                }
                else
                {
                    res.msg = "记录不存在";
                    logger.LogWarning($"羊只采购信息不存在，ID: {dto.Id}");
                }

                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"羊只采购信息更新异常: {ex.Message}");
                throw ex;
            }
        }

        /// <summary>
        /// 羊只采购查询
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>查询结果</returns>
        public async Task<ApiResult<List<SheepPurchaseResultDto>>> SearchSheepPurchase(SearchSheepPurchaseDto dto)
        {
            logger.LogInformation("开始查询羊只采购信息");
            var res = new ApiResult<List<SheepPurchaseResultDto>>();
            try
            {
                // 查询采购数据，增加SheepTypeId过滤
                var query = sheepPurchaseRepository.Getlist().Where(x => !x.IsDele);
                if (dto.SheepTypeId != null)
                {
                    query = query.Where(x => x.SheepTypeId == dto.SheepTypeId);
                }
                if (dto.PenId != null)
                {
                    query = query.Where(x => x.PenId == dto.PenId);
                }
                if (dto.PurchaserId != null)
                {
                    query = query.Where(x => x.PurchaserId == dto.PurchaserId);
                }
                var list = query.ToList();
                var dtos = mapper.Map<List<SheepPurchaseResultDto>>(list);

                // 关联羊只类型名称
                foreach (var item in dtos)
                {
                    if (item.SheepTypeId != null)
                    {
                        var sheepType = await db.SheepTypes.FindAsync(item.SheepTypeId);
                        item.SheepTypeName = sheepType?.TypeName;
                    }
                    if (item.PenId != null)
                    {
                        var house = await db.housetypeinfos.FindAsync((int)item.PenId.Value);
                        item.PenName = house?.DongsheName;
                    }
                    if (item.PurchaserId != null)
                    {
                        var purchaser = await db.Userinfos.FindAsync(item.PurchaserId);
                        item.PurchaserName = purchaser?.UserName;
                    }
                }

                res.success("查询成功", dtos);
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"查询羊只采购信息异常: {ex.Message}");
                res.msg = $"查询失败: {ex.Message}";
                return res;
            }
        }

        /// <summary>
        /// 根据ID获取羊只采购详情
        /// </summary>
        /// <param name="id">羊只采购ID</param>
        /// <returns>羊只采购详情</returns>
        public async Task<ApiResult<SheepPurchaseResultDto>> GetSheepPurchaseById(long id)
        {
            logger.LogInformation($"获取羊只采购详情，ID: {id}");
            var res = new ApiResult<SheepPurchaseResultDto>();

            try
            {
                var entity = await sheepPurchaseRepository.GetValue(x => x.Id == id && !x.IsDele);

                if (entity != null)
                {
                    var result = mapper.Map<SheepPurchaseResultDto>(entity);
                    res.success("获取成功", result);
                    logger.LogInformation($"羊只采购详情获取成功，ID: {id}");
                }
                else
                {
                    res.msg = "记录不存在";
                    logger.LogWarning($"羊只采购信息不存在，ID: {id}");
                }

                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"获取羊只采购详情异常: {ex.Message}");
                throw ex;
            }
        }

        // 模拟栋舍实体
        private class BuildingSim
        {
            public long Id { get; set; }
            public string Name { get; set; }
        }
    }
}